import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { BaseService } from '@src/service/base/base.service';
import { StructUserEntity } from '@src/entities/sys/struct_user.entity';
import { Repository, getManager, EntityManager } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { AssiginUserDto } from '@src/controllers/admin/system/struct/dto';

@Injectable()
export class StructUserService extends BaseService {
  constructor(
    @InjectRepository(StructUserEntity)
    private readonly structUserRepository: Repository<StructUserEntity>,
  ) {
    super(structUserRepository);
  }

  /**
   * @Description: 给组织机构分配用户
   * @param {type}
   * @return:
   */
  async assignUser(data: AssiginUserDto): Promise<any> {
    const { structId, userList } = data;
    /**
     * 1.先将表中userId的删除
     * 2.重新插入数据
     */
    return getManager()
      .transaction(async (entityManager: EntityManager) => {
        await entityManager.delete(StructUserEntity, { structId: Number(structId) })
        for (const item of userList) {
          await entityManager.save(StructUserEntity, { structId, userId: Number(item) })
        }
      }).then(async () => {
        Logger.log('组织机构分配用户成功');
        return { result: true };
      }).catch((e) => {
        Logger.error('组织机构分配用户错误', e);
        throw new HttpException('组织机构分配用户错误', HttpStatus.BAD_REQUEST);
      });
  }

  /**
   * @Description: 给组织机构单独分配用户
   * @param {type}
   * @return:
   */
  async assignOneUser(data: AssiginUserDto): Promise<any> {
    const { structId, userList } = data;
    /**
     * 1.先将表中userId的删除
     * 2.重新插入数据
     */
    return getManager()
      .transaction(async (entityManager: EntityManager) => {
        await entityManager.delete(StructUserEntity, { userId: Number(userList[0]) })
        for (const item of userList) {
          await entityManager.save(StructUserEntity, { structId, userId: Number(item) })
        }
      }).then(async () => {
        Logger.log('组织机构分配用户成功');
        return { result: true };
      }).catch((e) => {
        Logger.error('组织机构分配用户错误', e);
        throw new HttpException('组织机构分配用户错误', HttpStatus.BAD_REQUEST);
      });
  }
}
